package com.iqilu.ksd.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.DefaultImageBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.ConvertUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/11/11.
 */

public class LiveCoverActivity extends BaseActivity implements View.OnClickListener,EasyPermissions.PermissionCallbacks{

    private static final String TAG = "LiveCoverActivity";

    private String picPath;
    private ArrayList<DefaultImageBean> list;
    private Intent resultIntent;
    private MyAdapter adapter;;

    private ImageView btLeft;
    private TextView tvTitle;
    private ImageView btAlbum;
    private ImageView btPhoto;
    private GridView gvList;

    private static final int PER_ALBUM = 1001;
    private static final int PER_PHOTO = 1002;
    private static final int REQUEST_FROM_ALBUM = 2001;
    private static final int REQUEST_FROM_PHOTO = 2002;
    private static final int REQUEST_FROM_CROP = 2003; //裁剪

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_livecover);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        resultIntent = new Intent();
    }

    private void initView(){
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        btAlbum = getView(R.id.bt_album);
        btPhoto = getView(R.id.bt_photo);
        gvList = getView(R.id.gv_list);
        btLeft.setOnClickListener(this);
        btAlbum.setOnClickListener(this);
        btPhoto.setOnClickListener(this);
        adapter = new MyAdapter();
        gvList.setAdapter(adapter);
        gvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title = list.get(position).getTitle();
                String thumb = list.get(position).getThumb();
                resultIntent.putExtra("title", title);
                resultIntent.putExtra("thumb", thumb);
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }
        });
        tvTitle.setText(getString(R.string.live_cover_title));
        getList();
    }

    @AfterPermissionGranted(PER_ALBUM)
    private void fromAlbum() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
        if(EasyPermissions.hasPermissions(this,perms)) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_FROM_ALBUM);
        }else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_camera_storage), PER_ALBUM, perms);
        }
    }

    @AfterPermissionGranted(PER_PHOTO)
    private void fromPhoto(){
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
        if(EasyPermissions.hasPermissions(this,perms)){
            picPath = CacheUtils.getCacheDir(this) + System.currentTimeMillis() + ".jpg";
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picPath)));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, REQUEST_FROM_PHOTO);
        }else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_camera_storage), PER_PHOTO, perms);
        }
    }

    private void getList(){
        String url = Api.URL_LIVE_DEFAULTIMAGE;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                list = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<DefaultImageBean>>(){});
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_left:
                finish();
                break;
            case R.id.bt_album:
                fromAlbum();
                break;
            case R.id.bt_photo:
                fromPhoto();
                break;
            default:
                break;
        }

    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(LiveCoverActivity.this).inflate(R.layout.list_item_live_defaultimage, null);
                holder.layContent = (RelativeLayout) convertView.findViewById(R.id.lay_content);
                holder.imgThumb = (SimpleDraweeView) convertView.findViewById(R.id.img_thumb);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            int width = (ScreenUtils.getScreenWidth(LiveCoverActivity.this) - ConvertUtils.dp2px(LiveCoverActivity.this, 22)) / 2;
            int height = width / 16 * 9;
            ViewGroup.LayoutParams params = holder.layContent.getLayoutParams();
            params.width = width;
            params.height = height;
            holder.layContent.setLayoutParams(params);
            holder.imgThumb.setImageURI(Uri.parse(list.get(position).getThumb()));
            return convertView;
        }

        class ViewHolder {
            SimpleDraweeView imgThumb;
            RelativeLayout layContent;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if(requestCode == REQUEST_FROM_CROP){ //裁剪完
            String thumb = data.getStringExtra("thumb");
            resultIntent.putExtra("thumb",thumb);
            setResult(Activity.RESULT_OK, resultIntent);
            finish();
            return;
        }
        if (requestCode == REQUEST_FROM_ALBUM) {
            ContentResolver resolver = getContentResolver();
            String[] proj = {MediaStore.Images.Media.DATA};
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);
                Cursor cursor = managedQuery(uri, proj, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                picPath = cursor.getString(column_index);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.i(TAG,"uri.getPath="+picPath);
        }
        Intent intent = new Intent(this, CropActivity.class);
        intent.putExtra("picPath", picPath);
        startActivityForResult(intent, REQUEST_FROM_CROP);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_camera_storage))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }
}
